<template>
  <div class="sos-phone-container">
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="地区编码">
          <el-input
            v-model="searchForm.cityCode"
            placeholder="请输入地区编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="地区">
          <el-input
            v-model="searchForm.remark"
            placeholder="请输入地区信息"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="openAddDialog">新增急救电话</el-button>
        </div>
      </div>

      <el-table :data="tableData" v-loading="tableLoading" border>
        <el-table-column prop="cityCode" label="地区编码" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="140" />
        <el-table-column prop="remark" label="地区" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column prop="updateTime" label="更新时间" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button text type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button text type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @closed="handleDialogClosed"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px">
        <el-form-item label="地区" prop="cityCode">
          <el-cascader
            v-model="city"
            :options="optionsnative_place"
            filterable
            clearable
            :props="{ checkStrictly: false }"
            @change="areaHandleChange"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            maxlength="20"
            clearable
          />
        </el-form-item>
        <el-form-item label="地区" prop="remark">
          <el-input
            v-model="formData.remark"
            placeholder="请输入地区"
            type="textarea"
            :rows="3"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  import { SosPhoneService } from '@/api/sosApi'
  import type {
    SosPhoneItem,
    SosPhoneQuery,
    SosPhoneSaveParam,
    SosPhoneUpdateParam
  } from '@/api/model/sosModel'
  import { ApiStatus } from '@/utils/http/status'
  import { provinceAndCityData, codeToText } from 'element-china-area-data'
  const optionsnative_place = provinceAndCityData
  const tableData = ref<SosPhoneItem[]>([])
  const tableLoading = ref(false)
  const total = ref(0)
  const city = ref<string[]>([])
  const searchForm = reactive<SosPhoneQuery>({
    cityCode: '',
    phone: '',
    remark: '',
    page: 1,
    pageSize: 10
  })

  const fetchList = async () => {
    tableLoading.value = true
    try {
      const res = await SosPhoneService.getPage(searchForm)
      if (String(res.code) === String(ApiStatus.success) && res.data) {
        const pageData = res.data
        tableData.value = pageData.list || []
        total.value = pageData.total || 0
      } else {
        ElMessage.error(res.message || '获取列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取列表失败')
    } finally {
      tableLoading.value = false
    }
  }
  const areaHandleChange = (value: any) => {
    if (!Array.isArray(value) || value.length < 2) {
      formData.cityCode = ''
      formData.remark = ''
      return
    }
    const provinceCode = String(value[0])
    const cityCode = String(value[1])
    const normalizedCityCode = cityCode.length === 4 ? `${cityCode}00` : cityCode
    const text = [codeToText[provinceCode], codeToText[normalizedCityCode] || codeToText[cityCode]]
      .filter(Boolean)
      .join('/')
    formData.cityCode = normalizedCityCode
    formData.remark = text || ''
    formRef.value?.validateField('cityCode').catch(() => {})
  }
  const handleSearch = () => {
    searchForm.page = 1
    fetchList()
  }

  const handleReset = () => {
    searchForm.cityCode = ''
    searchForm.phone = ''
    searchForm.remark = ''
    searchForm.page = 1
    searchForm.pageSize = 10
    fetchList()
  }

  const handleSizeChange = (size: number) => {
    searchForm.pageSize = size
    searchForm.page = 1
    fetchList()
  }

  const handleCurrentChange = (page: number) => {
    searchForm.page = page
    fetchList()
  }

  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const submitLoading = ref(false)
  const formRef = ref<FormInstance>()
  const formData = reactive<SosPhoneSaveParam & { id?: number }>({
    cityCode: '',
    phone: '',
    remark: ''
  })

  const formRules: FormRules = {
    cityCode: [
      { required: true, message: '请选择地区', trigger: 'change' },
      { max: 50, message: '地区编码不能超过50个字符', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1\d{10}$|^\+?\d{5,20}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    remark: [
      { required: true, message: '请输入备注信息', trigger: 'blur' },
      { min: 1, max: 255, message: '备注长度需要在1-255个字符之间', trigger: 'blur' }
    ]
  }

  const dialogTitle = computed(() => (isEdit.value ? '编辑急救电话' : '新增急救电话'))

  const resetForm = () => {
    formRef.value?.resetFields()
    formData.id = undefined
  }

  const openAddDialog = () => {
    isEdit.value = false
    city.value = []
    resetForm()
    dialogVisible.value = true
  }

  const findCityPathByCode = (code?: string): string[] => {
    if (!code) {
      return []
    }
    const normalized = code.toString()
    for (const province of optionsnative_place as any[]) {
      const provinceCode = String(province.value)
      const children = province.children || []
      const match = children.find((child: any) => String(child.value) === normalized)
      if (match) {
        return [provinceCode, String(match.value)]
      }
      if (normalized.endsWith('00')) {
        const shortCode = normalized.substring(0, 4)
        const shortMatch = children.find((child: any) => String(child.value) === shortCode)
        if (shortMatch) {
          return [provinceCode, String(shortMatch.value)]
        }
      }
    }
    return []
  }

  const openEditDialog = (row: SosPhoneItem) => {
    isEdit.value = true
    formData.id = row.id
    formData.cityCode = row.cityCode || ''
    formData.phone = row.phone || ''
    formData.remark = row.remark || ''
    city.value = findCityPathByCode(row.cityCode)
    dialogVisible.value = true
  }

  const handleDialogClosed = () => {
    resetForm()
    city.value = []
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      const valid = await formRef.value.validate()
      if (!valid) return
      submitLoading.value = true
      const payload = {
        cityCode: formData.cityCode,
        phone: formData.phone,
        remark: formData.remark
      }
      if (isEdit.value && formData.id) {
        await SosPhoneService.update({ ...(payload as SosPhoneUpdateParam), id: formData.id })
        ElMessage.success('编辑成功')
      } else {
        await SosPhoneService.save(payload)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchList()
    } catch (error) {
      console.error(error)
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  }

  const handleDelete = async (row: SosPhoneItem) => {
    if (!row.id) return
    try {
      await ElMessageBox.confirm(`确认删除【${row.remark || row.phone}】吗？`, '提示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning'
      })
      await SosPhoneService.remove({ id: row.id })
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && searchForm.page > 1) {
        searchForm.page -= 1
      }
      fetchList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error(error)
        ElMessage.error('删除失败')
      }
    }
  }

  onMounted(() => {
    fetchList()
  })
</script>

<style scoped lang="scss">
  .sos-phone-container {
    padding: 16px;

    .filter-card {
      margin-bottom: 16px;
    }

    .table-card {
      .table-toolbar {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;

        .toolbar-left {
          display: flex;
          gap: 12px;
        }
      }

      .table-pagination {
        display: flex;
        justify-content: flex-end;
        padding-top: 16px;
      }
    }
  }
</style>